package com.hefan.mgmt.controller.task;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.hefan.schedule.model.ScheduleServer;
import com.hefan.schedule.model.ScheduleStrategy;
import com.hefan.schedule.model.ScheduleTaskType;
import com.hefan.schedule.service.IScheduleExecuteRecordService;
import com.hefan.schedule.taskmanager.ConsoleManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;
import java.util.Map;

@RequestMapping("/task")
@Controller
public class TaskController {
	
	private static Logger logger = LoggerFactory.getLogger(TaskController.class);
	
	@Autowired
	private IScheduleExecuteRecordService scheduleExecuteRecordService;

	@RequestMapping("/index")
	public String index(HttpServletRequest request) throws Exception {
		List<ScheduleTaskType> taskTypes = ConsoleManager
				.getScheduleDataManager().getAllTaskTypeBaseInfo();
//		ConsoleManager.getScheduleDataManager().deleteTaskType("ActivityStep2OverTimeTask");
//		ConsoleManager.getScheduleDataManager().deleteTaskType("AssetTask");
//		ConsoleManager.getScheduleDataManager().deleteTaskType("InvestRecordTask");
//		ConsoleManager.getScheduleDataManager().deleteTaskType("LoanInvestorLoanAssetTask");
//		ConsoleManager.getScheduleDataManager().deleteTaskType("OutAssetTask");
//		ConsoleManager.getScheduleDataManager().deleteTaskType("PlatformStatisticsTask");
//		ConsoleManager.getScheduleDataManager().deleteTaskType("RankingListTask");
//		ConsoleManager.getScheduleDataManager().deleteTaskType("rankingListTask");
//		
//		ConsoleManager.getScheduleStrategyManager().deleteMachineStrategy("ActivityStep2OverTimeTask-Strategy", true);
//		ConsoleManager.getScheduleStrategyManager().deleteMachineStrategy("AssetTask-Strategy", true);
//		ConsoleManager.getScheduleStrategyManager().deleteMachineStrategy("InvestRecordTask-Strategy", true);
//		ConsoleManager.getScheduleStrategyManager().deleteMachineStrategy("LoanInvestorLoanAssetTask-Strategy", true);
//		ConsoleManager.getScheduleStrategyManager().deleteMachineStrategy("OutAssetTask-Strategy", true);
//		ConsoleManager.getScheduleStrategyManager().deleteMachineStrategy("PlatformStatisticsTask-Strategy", true);
//		ConsoleManager.getScheduleStrategyManager().deleteMachineStrategy("RankingListTask-Strategy", true);
//		ConsoleManager.getScheduleStrategyManager().deleteMachineStrategy("rankingListTask-Strategy", true);
		
		request.setAttribute("taskTypes", taskTypes);
		return "/task/index";
	}
	
	/**
	 * 添加/修改任务
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 * @author daijian.song
	 * @since 2015年8月3日 上午10:37:35
	 * @version 1.0.0
	 */
	@RequestMapping("/taskTypeEdit")
	public String taskTypeEdit(HttpServletRequest request) throws Exception{
		String taskTypeName = request.getParameter("taskType");
	    ScheduleTaskType taskType =  ConsoleManager.getScheduleDataManager().loadTaskTypeBaseInfo(taskTypeName);
	    ScheduleStrategy scheduleStrategy = ConsoleManager.getScheduleStrategyManager().loadStrategy(taskTypeName + "-Strategy");
	    boolean isNew = false;
	    String actionName ="editTaskType";
		if(taskType == null){
			// 新增任务
			taskType = new ScheduleTaskType();
			taskType.setBaseTaskType("");
			taskType.setDealBeanName("");
			taskType.setTaskDescription("");
			isNew = true;
			actionName ="createTaskType";
		}
		if(scheduleStrategy != null){
			String ips = "";
			for (String ip : scheduleStrategy.getIPList()) {
				ips += ip + ",";
			}
			if(scheduleStrategy.getIPList().length > 0){
				ips = ips.substring(0, ips.length()-1);
			}
			request.setAttribute("ips", ips);
		}
		request.setAttribute("actionName", actionName);
		request.setAttribute("taskType", taskType);
		request.setAttribute("isNew", isNew);
		return "/task/taskTypeEdit";
	}
	
	
	/**
	 * 保存任务
	 * @param request
	 * @param response
	 * @return
	 * @author daijian.song
	 * @since 2015年8月3日 下午4:31:02
	 * @version 1.0.0
	 * @throws UnsupportedEncodingException 
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/taskTypeSave",produces = "text/html;charset=UTF-8")
	@ResponseBody
	public String taskTypeSave(HttpServletRequest request) throws UnsupportedEncodingException{
		request.setCharacterEncoding("UTF-8");
		String mydata = request.getParameter("mydata");
		Map<String, String> params = JSONObject.parseObject(mydata, Map.class);
		String action = params.get("action");
		String result = "";
		String baseTaskType = params.get("taskType");
		String dealBean = params.get("dealBean");
		String permitRunStartTime = params.get("permitRunStartTime");
		String permitRunEndTime = params.get("permitRunEndTime");
		String sts = params.get("sts");
		String taskDescription = params.get("taskDescription");
		String ips = params.get("ips");
		
		logger.info("保存任务params"+params+"开始");
		
		try {
			if (action.equalsIgnoreCase("createTaskType")||action.equalsIgnoreCase("editTaskType")) {
				ScheduleTaskType taskType = new ScheduleTaskType();
				taskType.setBaseTaskType(baseTaskType);
				taskType.setDealBeanName(dealBean);;
				taskType.setPermitRunStartTime(permitRunStartTime);
				taskType.setPermitRunEndTime(permitRunEndTime);		
				taskType.setTaskParameter("");	
				taskType.setTaskItems(ScheduleTaskType.splitTaskItem("1"));
				taskType.setSts(sts);
				taskType.setTaskDescription(taskDescription);
				//TODO 添加成功后，添加默认策略
				ScheduleStrategy scheduleStrategy = new ScheduleStrategy();
				scheduleStrategy.setStrategyName(baseTaskType+"-Strategy");
				scheduleStrategy.setKind(ScheduleStrategy.Kind
						.valueOf("Schedule"));
				scheduleStrategy.setTaskName(baseTaskType);
				scheduleStrategy.setTaskParameter("");
				
				if (ips == null) {
					scheduleStrategy.setIPList(new String[0]);
				} else {
					scheduleStrategy.setIPList(ips.split(","));
				}

				scheduleStrategy.setNumOfSingleServer(0);
				scheduleStrategy.setAssignNum(1);
				
				if(action.equalsIgnoreCase("createTaskType")){
					ConsoleManager.getScheduleDataManager().createBaseTaskType(taskType);
					ConsoleManager.getScheduleStrategyManager().createScheduleStrategy(scheduleStrategy);

					result = "任务" + baseTaskType + "创建成功！！！！";
				}else{
					ConsoleManager.getScheduleDataManager().updateBaseTaskType(taskType);
					ConsoleManager.getScheduleStrategyManager().updateScheduleStrategy(scheduleStrategy);
					result = "任务" + baseTaskType + "修改成功！！！！";
				}
			} else{
				throw new Exception("不支持的操作：" + action);
			}
		} catch (Throwable e) {
			logger.error("保存任务时，出现异常",e.getMessage());
			result ="ERROR:" + e.getMessage(); 
		}
		logger.info(result);
		return JSONArray.toJSONString(URLEncoder.encode(result,"UTF-8"));
	}
	
	/**
	 * 任务管理
	 * @param request
	 * @param response
	 * @return
	 * @author daijian.song
	 * @since 2015年8月3日 下午5:58:40
	 * @version 1.0.0
	 */
	@RequestMapping(value = "/taskTypeManager",produces = "text/html;charset=UTF-8")
	@ResponseBody
	public String taskTypeManager(HttpServletRequest request) throws UnsupportedEncodingException {
		String action = request.getParameter("action");
		String baseTaskType = request.getParameter("taskType");
		String result = "";
		try {
			if (action.equalsIgnoreCase("clearTaskType")) {
				ConsoleManager.getScheduleDataManager().clearTaskType(
						baseTaskType);
				result = "任务" + baseTaskType + "运行期信息清理成功！！！！";
			} else if (action.equalsIgnoreCase("deleteTaskType")) {
				ConsoleManager.getScheduleDataManager().deleteTaskType(
						baseTaskType);
				result = "任务" + baseTaskType + "删除成功！！！！";
			}
			else if (action.equalsIgnoreCase("pauseTaskType")) {
				ConsoleManager.getScheduleDataManager().pauseAllServer(baseTaskType);
				result = "任务" + baseTaskType + "停止成功！！！！";
			} else if (action.equalsIgnoreCase("resumeTaskType")) {
				ConsoleManager.getScheduleDataManager().resumeAllServer(baseTaskType);
				result = "任务" + baseTaskType + "重启成功！！！！";
			}else{
				throw new Exception("不支持的操作：" + action);
			}
		} catch (Throwable e) {
			logger.error("管理任务时，出现异常",e.getMessage());
			result ="ERROR:" + e.getMessage(); 
		}
		logger.info(result);
		return JSONArray.toJSONString(URLEncoder.encode(result,"UTF-8"));
	}
	
	/**
	 * 获取任务运行时详情
	 * @param request
	 * @param response
	 * @return
	 * @author daijian.song
	 * @since 2015年8月3日 下午6:25:22
	 * @version 1.0.0
	 * @throws Exception 
	 */
	@RequestMapping("/taskRunTime")
	public String taskRunTime(HttpServletRequest request) throws Exception{
		String taskType = request.getParameter("taskType");
		List<ScheduleServer> serverList = ConsoleManager.getScheduleDataManager().selectAllValidScheduleServer(taskType);
		//TODO 添加执行历史
		List<Map<String,Object>> scheduleExecuteRecordList = scheduleExecuteRecordService.getScheduleExecuteRecordList(taskType);
		request.setAttribute("taskType", taskType);
		request.setAttribute("scheduleExecuteRecordList", scheduleExecuteRecordList);
		request.setAttribute("serverList", serverList);
		return "/task/taskRunTime";
	}
}